package com.lqs.sofp.servlet;

import com.lqs.sofp.entity.User;
import com.lqs.sofp.service.UserService;
import com.lqs.sofp.service.impl.UserServiceImpl;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet(name = "UserLoginServlet", value = "/User/uls")
public class UserLoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.收参
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        //收参测试（check）
        //System.out.println(username + "\t" + password + "在servlet层收参成功！");

        //2.调用登录服务
        UserService userLogin = new UserServiceImpl();
        User user = userLogin.login(username, password);

        //测试数据回传。
        //System.out.println(user);

        if (user != null) {
            //说明登录成功。
            //存储在session作用域
            HttpSession session = request.getSession();
            session.setAttribute("User", user);
            //将业务转发到另一个用来执行进入社区页面的servlet
            RequestDispatcher dispatcher =  request.getRequestDispatcher("/html/community");
            dispatcher.forward(request, response);
        } else {
            //登录不成功重定向到登录页面。
            response.sendRedirect(request.getContextPath() + "/index.jsp");
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
